package com.speedtickets.rest.validators;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.speedtickets.rest.exceptions.ValidationException;

public class Validator {
	
	private List<String>invalidFields = new ArrayList<String>();
	
	private Boolean isInvalid = false;
	
	public void validate( Object o ) throws IllegalArgumentException, IllegalAccessException, ValidationException{
		isInvalid = false;
		Class<?> clazz = o.getClass();
		Field[] classFields = clazz.getDeclaredFields();
		for (Field field : classFields) {
			if(!field.getName().equals("id") && !field.getName().equals("fine")
					&& !field.getName().equals("ticketIds")){	
				field.setAccessible(true);
				Object obj = field.get(o);
				if(obj == null || obj == ""){
					isInvalid = true;
					invalidFields.add(field.getName());
				}
				field.setAccessible(false);
			}
		}
		if(isInvalid){
			throw new ValidationException(buildExceptionMessage());
		}
	}
	
	private String buildExceptionMessage(){
		String message = "Required fields: ";
    	message += "(";
		for (String field  : invalidFields) {
			message += " '" + field + "' ";
		}
		message += ")";
    	return message;
	}

}
